package test;
import util.DBUtil;

import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.Connection;
import java.util.*;
public class ExecuteDemo {
    public void ExecuteSql(String sql) throws Exception{
        Connection conn = null;
        ResultSet rs = null;
        try{
            conn = DBUtil.getConnection();
            Statement stmt = conn.createStatement();
            boolean hasResultSet = stmt.execute(sql);
            if(hasResultSet){
                rs = stmt.getResultSet();
                while(rs.next()){
                    System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t");
                }
                System.out.println();
            }
            else{
                System.out.println("The records affected by the SQL statemen:"+stmt.getUpdateCount());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(rs!=null) rs.close();
            conn.close();
        }
    }

    public static void main(String[] args) throws Exception {
        ExecuteDemo executeObj = new ExecuteDemo();
        executeObj.ExecuteSql("create table my_test"
                + "(test_id int primary key, " + "test_name varchar(255))");
        executeObj.ExecuteSql("insert into my_test(test_id,test_name)"+"values(1,'zhangsan')");
        executeObj.ExecuteSql("insert into my_test(test_id,test_name)"
                +"values(2,'lisi')");
        executeObj.ExecuteSql("insert into my_test(test_id,test_name)"
                +"values(3,'wangwu')");
        executeObj.ExecuteSql("select * from my_test");
        executeObj.ExecuteSql("drop table my_test");
    }
}